<template>
	<view class="my-login">
		<view style="display: flex;flex-direction: column;justify-content: center;align-items: center;">
			<uni-icons type="contact" size="100"></uni-icons>
			<button class="login" open-type="getUserInfo" @getuserinfo="getuserinfo">一键登录</button>
			<view class="login-text">登录后尽享更多权益</view>
		</view>
	</view>
</template>

<script>
	import {mapMutations} from "vuex"
	export default {
		name: "my-login",
		data() {
			return {
			};
		},
		methods: {
			...mapMutations('m_user',["updateUserInfo"]),
			getuserinfo(e) {
				console.log(e)
				if(e.detail.errMsg==="getUserInfo:ok"){
					this.updateUserInfo(e.detail.userInfo)
					console.log(e.detail);
					this.getToken(e.detail)
					
				}
			},
			// 调用登录接口，换取永久的 token
			async getToken(info) {
			  // 调用微信登录接口
			  const [err, res] = await uni.login({
				  provider:"weixin"
			  }).catch(err => err)
			  console.log(res);
			  // 判断是否 uni.login() 调用失败
			  if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
			  // 准备参数对象
			  const query = {
			    code: res.code,
			    encryptedData: info.encryptedData,
			    iv: info.iv,
			    rawData: info.rawData,
			    signature: info.signature
			  }
			  // 换取 token
			  const { data: loginResult } = await uni.$http.post('/users/wxlogin', query)
			  console.log(loginResult);
			  if (loginResult.meta.status !== 200) return uni.$showMsg('登录失败！')
			  uni.$showMsg('登录成功')
			}
			}
		}
</script>

<style scoped>
	.my-login {
		width: 100%;
		height: 100%;
		position: fixed;
		display: flex;
		justify-content: center;
		align-items: center;

	}

	.login {
		background-color: #c00000;
		width: 300px;
		padding: 8px 0;
		color: white;
		text-align: center;
		border-radius: 20px;
		margin-bottom: 10px;
	}
</style>
